package middleware

import (
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/db"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/model"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/wssecurity"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
)

// WSSecurity xwsse
// Authorization=`WSSE profile="UsernameToken"`
// X-WSSE: UsernameToken Username="bob", PasswordDigest="quR/EWLAV4xLf9Zqyw4pDmfV9OY=", Nonce="d36e316282959a9ed4c89851497a717f", Created="2006-01-02T15:04:05Z"
// PasswordDigest=sm3(Nonce + Created + AppSecret)
// Nonce 随机数
// Created 时间， 格式：2006-01-02T15:04:05Z
func WSSecurity() gin.HandlerFunc {
	return func(c *gin.Context) {
		authorization := c.GetHeader("Authorization")
		xwsse := c.GetHeader("X-WSSE")
		xwsseInstance, err := wssecurity.Check(authorization, xwsse, getAppSecret)
		if err != nil {
			global.Log.Error("非法请求, X-WSSE无效", zap.Any("err", err))
			c.JSON(http.StatusUnauthorized, model.Fail("非法请求"))
			c.Abort()
		}
		// 保存header
		c.Header("Authorization", authorization)
		c.Header("X-WSSE", xwsse)
		// 保存digest，用于sm4加密
		c.Set("SM4-KEY", xwsseInstance.PasswordDigest[0:16])
		c.Next()
	}
}

// 获取appSecret
func getAppSecret(appKey string) (appSecret string, err error) {
	session := db.Session()
	defer session.Close()
	_, err = session.Table("interface_auth").Select("app_secret").
		Where("app_key=?", appKey).
		Get(&appSecret)
	return
}
